package hoang.hut.app.utility.file;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.widget.ImageView;

public class FileHandle {

	/**
	 * copy file
	 * 
	 * @param from: full path: /data/app/baonet-1.apk
	 * @param to sdcard/baonet.apk
	 * @return
	 */
	public static boolean copyFile(String from, String to) {
		try {
			@SuppressWarnings("unused")
			int bytesum = 0;
			int byteread = 0;
			File oldfile = new File(from);
			if (oldfile.exists()) {
				InputStream inStream = new FileInputStream(from);
				FileOutputStream fs = new FileOutputStream(to);
				byte[] buffer = new byte[1444];
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread;
					fs.write(buffer, 0, byteread);
				}
				inStream.close();
				fs.close();
			}
			return true;
		} catch (Exception e) {
			System.out.println(e.getMessage());
			return false;
		}
	}

	/**
	 * read file to sdcard
	 * 
	 * @param path
	 * @return
	 */
	@SuppressWarnings("resource")
	public String readFromSD(String path) {
		File file = new File(path);
		StringBuilder text = new StringBuilder();
		try {
			BufferedReader br = new BufferedReader(new FileReader(file));
			String line;
			while ((line = br.readLine()) != null) {
				text.append(line);
				text.append('\n');
			}
		} catch (IOException e) {
		}
		return text.toString();
	}

	/**
	 * download file from server
	 * 
	 * @param url
	 * @param dest_file_path
	 */
	public void downloadFile(String url, String dest_file_path) {
		try {
			File dest_file = new File(dest_file_path);
			URL u = new URL(url);
			URLConnection conn = u.openConnection();
			int contentLength = conn.getContentLength();

			DataInputStream stream = new DataInputStream(u.openStream());

			byte[] buffer = new byte[contentLength];
			stream.readFully(buffer);
			stream.close();

			DataOutputStream fos = new DataOutputStream(new FileOutputStream(
					dest_file));
			fos.write(buffer);
			fos.flush();
			fos.close();

		} catch (FileNotFoundException e) {
			return;
		} catch (IOException e) {
			return;
		}
	}
	/**
	 * load image to Asset folder
	 * 
	 * @param imv
	 * @param filename
	 * @param context
	 */
	public void loadDataFromAsset(ImageView imv, String filename,
			Context context) {
		try {

			InputStream is = ((Activity) context).getAssets().open(filename);
			Drawable d = Drawable.createFromStream(is, null);
			imv.setImageDrawable(d);
		} catch (IOException ex) {
			return;
		}
	}

}
